import 'dart:async';

import 'package:erp/Entity/WareHouse.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/UI/Components/EmbeddableStatefulWidget.dart';
import 'package:erp/UI/Components/MessageDialog.dart';
import 'package:erp/UI/Pages/BasicInformationManagementPages/WareHousePages/WareHousePage.dart';
import 'package:erp/global.dart';
import 'package:flutter/material.dart';


Future<bool> showWareHauseEditDialog(BuildContext context, WareHouse data, [bool creationMode = true]) async {

  var nameTextController = TextEditingController(text:  data.name);
  var descriptionTextController = TextEditingController(text:  data.memo);

  return showDialog(context: context, builder: (context) => AlertDialog(
    title: Center(child: Text("ئامبار ئۇچۇرىنى تەھرىرلەڭ")),
    content: EmbeddedWidget(
      initEvent: (widget){
        widget.eventIds = [
          widget.bus.subscribe(Events.WAREHOUSE_INSERT_SUCCESS, (bus, _){
            Navigator.of(context).pop(true);
          }),
          widget.bus.subscribe(Events.WAREHOUSE_UPDATE_SUCCESS, (bus, _){
            Navigator.of(context).pop(true);
          }),
          widget.bus.subscribe(Events.WAREHOUSE_INSERT_ERROR, (bus, error){
            showMessageDialog(context, title: "قوشۇش مەغلۇپ بولدى", content: error.toString());
          }),
          widget.bus.subscribe(Events.WAREHOUSE_UPDATE_ERROR, (bus, error){
            showMessageDialog(context, title: "يىڭىلاش مەغلۇپ بولدى", content: error.toString());
          })
        ];
      },
      widgetBuilder: (context, widget){
        return Wrap(
          direction: Axis.vertical,
          children: <Widget>[
            Container(
              width: 250.0,
              child: TextField(
                controller: nameTextController,
                decoration: InputDecoration(
                    labelText: "ئىسمى",
                    hintText: "ئىسمىنى كىرگۈزۈڭ"
                ),
                onChanged: (text) => data.name = text,
              ),
            ),
            Container(
              width: 250.0,
              child: TextField(
                controller: descriptionTextController,
                decoration: InputDecoration(
                    labelText: "ئىزاھات",
                    hintText: "ئىزاھاتىنى كىرگۈزۈڭ"
                ),
                onChanged: (text) => data.memo = text,
              ),
            ),
          ],
        );
      }
    ),
    actions: <Widget>[
      FlatButton(onPressed: (){
        Navigator.of(context).pop(false);
      }, child: Text("بىكار قىلىش")),
      FlatButton(onPressed: (){
        if (creationMode){
          globalBus.publish(Events.WAREHOUSE_INSERT_REQUEST, data);
        }
        else {
          globalBus.publish(Events.WAREHOUSE_UPDATE_REQUEST, data);
        }
      }, child: Text("جەزىملەشتۈرۈش")),
    ],
  ), barrierDismissible: false);
}

